const mongoose = require('mongoose');
const db = 'mongodb://127.0.0.1:27017/meiData';
mongoose.Promise = global.Promise;

exports.connect = () => {
    let maxConnectTimes = 0;
    return new Promise(resolve => {
        if (process.env.NODE_ENV !== 'production') {
            mongoose.set('debug',true)
        }

        mongoose.connect(db)

        // 网络终端 或者服务器重启
        mongoose.connection.on('disconnected',() => {
            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            }  else {
                throw new Error('数据库挂了')
            }
        });

        mongoose.connection.on('error',(err) => {
            maxConnectTimes ++;
            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            }  else {
                throw new Error('数据库挂了')
            }
        })

        mongoose.connection.once('open',(err) => {
            resolve()
            console.log('数据库链接成功');
        })
    })
}

exports.mongoose = mongoose;